package cn.flant.io.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class LinedMessageHandler extends MessageHandler {
	private static final char[] LINE_SEPERATOR = { '\r', '\n' };
	private BufferedReader reader;
	private BufferedWriter writer;

	@Override
	public void onConnected(Socket socket) throws IOException {
		reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), getCharset()));
		writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), getCharset()));
	}

	@Override
	public Object readMessage() throws IOException {
		return reader.readLine();
	}

	@Override
	public void sendMessage(Object message) throws IOException {
		String line = message == null ? "" : message.toString();
		writer.write(line);
		writer.write(LINE_SEPERATOR);
		writer.flush();
	}

	@Override
	public void onClosed() {
		if (reader != null) {
			try {
				reader.close();
			} catch (Exception e) {
			}
			reader = null;
		}
		if (writer != null) {
			try {
				writer.close();
			} catch (Exception e) {
			}
			writer = null;
		}
	}
}
